public class Body {
    public String name;
    public double mass;
    public Vector loc;
    public Vector velocity;
    public static final double G = 1.0;

    public Body(double lx, double ly, double vx, double vy, double mass) {
        this.mass = mass;
        this.loc = new Vector(lx, ly);
        this.velocity = new Vector(vx, vy);
    }

    public Vector forceFrom(Body that) {
        /**
         * F = G * m1 * m2 / r^2
         */
        double Gm1 = G * this.mass;
        double rx = that.loc.x - this.loc.x;
        double ry = that.loc.y - this.loc.y;
        double rr = rx * rx + ry * ry;
        double r = Math.sqrt(rr);
        double f = Gm1 * that.mass / rr;
        double fdx = f * rx / r;
        double fdy = f * ry / r;
        return new Vector(fdx, fdy);
    }

    /**
     * 让当前天体受到引力force的作用duration时间，更新速度和位置
     *
     * @param force
     * @param duration
     */
    public void updateStatus(Vector force, Double duration) {
        /**
         * F = ma -> a = F/m
         * v = at -> v = Ft/m
         */
        double tm = duration / this.mass;

        this.velocity.x += force.x * tm;
        this.velocity.y += force.y * tm;

        this.loc.x += this.velocity.x * duration;
        this.loc.y += this.velocity.y * duration;
    }

    @Override
    public String toString() {
        return "Body{" +
                "name='" + name + '\'' +
                ", mass=" + mass +
                ", loc=" + loc +
                ", velocity=" + velocity +
                '}';
    }
}